package cn.thinktool.bighand;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {

	private MsgHandler handler = new MsgHandler();
	private Thread  udpReceiver = null;
	private ListView pclist = null;
	private ServiceAdapter adapter = null;
	private List<ControlServiceInfo> list = new ArrayList<ControlServiceInfo>();
	
	//private final static int MSG_UDPATE_PC = 2013;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        udpReceiver = new Thread(new UDPThread());
        udpReceiver.start();
        
        ListView pclist = (ListView)this.findViewById(R.id.pclist);
        adapter = new ServiceAdapter(this, list);
        pclist.setAdapter(adapter);
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    public boolean handleMessage(Message msg){
    	if (msg.obj instanceof PrivateBroadCastProtocol){
    		PrivateBroadCastProtocol pbc = (PrivateBroadCastProtocol)msg.obj;
    		ControlServiceInfo csi = new ControlServiceInfo();
    		csi.setName(pbc.getName());
    		csi.setAddress(String.valueOf(pbc.getAddress()));
    		csi.setPort(pbc.getPort());
    		list.add(csi);
    		adapter.notifyDataSetChanged();
    	}
    	return false;
    }
    
    class MsgHandler extends Handler{
    	@Override
    	public void handleMessage(Message msg) {
    		// TODO Auto-generated method stub
    		if (MainActivity.this.handleMessage(msg)){
    			return;
    		}
    		super.handleMessage(msg);
    	}
    }
    
    class UDPThread implements Runnable {
    	@Override
    	public void run() {
    		//DatagramSocket server = new DatagramSocket(2253);
			byte[] recvbuf = new byte[1024];
			DatagramPacket recvpacket = new DatagramPacket(recvbuf, recvbuf.length);
			
			while(true){
				///server.receive(recvpacket);
				handlePacket(recvpacket);
				
				try {
					Thread.sleep(1500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
    		
    	}
    	
    	public void handlePacket(DatagramPacket packet){
    		PrivateBroadCastProtocol pbc = PrivateBroadCastProtocolDecoder.parse(packet);
    		if ( pbc != null ){
    			Message msg = new Message();
    			msg.obj = pbc;
    			MainActivity.this.handler.sendMessage(msg);
    		}
    	}
    }

    
}
